/* Filename: popen.c
 * Description: <TODO>
 * Last modified: humble 2021-01-28 09:22:42
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

static void usage(void)
{
#define USAGE "Usage:\n\
    Version 1.0.0\n"
    printf(USAGE);
}

static int test_popen1(void)
{
    int ret = -1;
#if 0
    //p = popen("ver","r"); /* DOS */
    //p = popen("uname 2>&1","r"); /* Unix */ //把错误输出重定向到标准输出
    FILE *p = popen("uname","r"); /* Unix */
    if(p == NULL){ puts("Unable to open process"); return -1; }
    char ch;
    while( (ch=fgetc(p)) != EOF) putchar(ch);
    pclose(p);
#else
    char cmd[256] = {0};
    sprintf(cmd, "ping 127.0.0.1 -c4");
    printf("cmd:%s\n", cmd);
    FILE *p = popen(cmd, "r");
    if(!p){ printf("popen(),'%s'\n", strerror(errno)); }
    //need select() to read?
    printf("reading\n");
    char info[1024] = {0};
    int len = fread(info, 1, sizeof(info), p);
    if(len <= 0){ printf("fread()->%d,failed\n", len); }
    else{ info[--len] = 0; ret = 0; printf("%s\n", info); }
    if(p){ pclose(p); }
#endif
    return ret;
}

static int get_mac(const char *iface)
{
    int ret = -1;
    char cmd[256] = {0};
    sprintf(cmd, "ifconfig %s|grep 'HWaddr'|awk '{print $5}'", iface);
    //sprintf(cmd, "ifconfig %s|grep 'ether'|awk '{print $2}'", iface);
    printf("cmd:%s\n", cmd);
    FILE *p = popen(cmd, "r");
    if(!p){ printf("popen(),'%s'\n", strerror(errno)); }
    char info[1024] = {0};
    int len = fread(info, 1, sizeof(info), p);
    if(len <= 0){ printf("fread()->%d,failed\n", len); }
    else{ info[--len] = 0; ret = 0; printf("%s\n", info); }
    if(p){ pclose(p); }
    return ret;
}

int main(int argc, char **argv)
{
    if(argc != 1){ fprintf(stderr, "argc !=1"); usage(); exit(1); }
    printf("==========test_popen1\n");
    test_popen1();
    printf("==========test_popen1\n");
    get_mac("enp5s0");
    return 0;
}
